package com.jav;

import com.jav.inter.Constantes;
import com.jav.per.PersisSetup;
import com.jav.per.Persistencia;
import com.sun.lwuit.Button;
import com.sun.lwuit.CheckBox;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.Container;
import com.sun.lwuit.TextField;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.TabbedPane;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.util.Resources;

public class SetupForm extends Form implements Constantes {

    private TextField tx_usuario, tx_clave;
    private TextArea tx_servidor;
    private TextArea tx_logs;
    private Button save;
    final CheckBox checkBox = new CheckBox("Enviar datos al guardar pedido.");
    TabbedPane tp = null;

    public SetupForm() {

        super("CONFIGURACIÓN");
        Resources res;
        try {

            setLayout(new BorderLayout());
            setTransitionInAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, false, 500));
            setTransitionOutAnimator(CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, true, 500));
            tp = new TabbedPane();


            res = Datos.getInstance().getRes();
            tx_usuario = new TextField("", TextField.NUMERIC);
            tx_servidor = new TextArea(3, 20, TextArea.URL);
            tx_logs = new TextArea(Datos.getInstance().getLogs().toString());
            tx_logs.setEditable(false);
            tx_servidor = new TextField("http://");
            tx_clave = new TextField("");
            tx_usuario.setConstraint(TextField.NUMERIC);
            tx_clave.setConstraint(TextField.PASSWORD);

            save = new Button("GUARDAR", res.getImage("add.png"));
            save.setAlignment(CENTER);

            /*Borra y crear el nuevo RecordStoreP*/
            save.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent evt) {
                    String user = tx_usuario.getText();
                    String clave = tx_clave.getText();
                    String url = tx_servidor.getText();
                    try {

                        if (user.trim().length() == 0) {
                            msgBox(0x8fff0000, "ERROR", "DEBE INGRESAR UNA CEDULA VALIDA");
                            tx_usuario.requestFocus();
                            return;
                        }
                        if (clave.trim().length() == 0) {
                            msgBox(0x8fff0000, "ERROR", "DEBE INGRESAR UNA CLAVE VALIDA");
                            tx_clave.requestFocus();
                            return;
                        }
                        if (url.trim().length() == 0 || !url.startsWith("http://")) {
                            msgBox(0x8fff0000, "ERROR", "DEBE INGRESAR UNA URL VALIDA, DEBE COMENZAR CON http://");
                            tx_servidor.requestFocus();
                            return;
                        }

                        PersisSetup setup = new PersisSetup();
                        setup.setUser(user.trim());
                        setup.setPass(clave.trim());
                        setup.setUrl_server(url.trim());
                        setup.setEnvio(checkBox.isSelected());
                        Persistencia p = new Persistencia(PERS_DATA_SERVER);
                        p.save(setup.persist());
                        msgBox(0x8f00ff00, "OK!", "GUARDADO EXITOSO!");
                        cargarDatos();

                    } catch (Exception e) {
                        msgBox(0x8f00ff00, "ERROR!", "error al guardar: " + e.getMessage());
                        System.out.println("error al guardar: " + e.getMessage());
                    }

                }
            });

            addCommand(new Command("Atrás", res.getImage("bck.png")) {

                public void actionPerformed(ActionEvent evt) {
                    CapMovil.getMainForm().show();
                }
            });

            /***********************************************************/
            Container cnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
            cnt.addComponent(createPair("user", tx_usuario, 10));
            cnt.addComponent(createPair("pass", tx_clave, 10));
            cnt.addComponent(createPair("server", tx_servidor, 10));
            cnt.addComponent(checkBox);
            cnt.addComponent(save);
            tp.addTab("DATOS", cnt);
            tp.addTab("LOGS", tx_logs);

            //addComponent("Center", tp);
            addComponent(BorderLayout.CENTER, tp);
            /***********************************************************/
            cargarDatos();

        } catch (Exception e) {
            Datos.getInstance().addLogs(e.getMessage());
        } finally {
            res = null;
        }
    }

    protected void cargarDatos() {

        PersisSetup pd = Datos.getInstance().getPersisSetup();
        if (pd != null) {
            this.tx_usuario.setText(pd.getUser());
            this.tx_clave.setText(pd.getPass());
            this.tx_servidor.setText(pd.getUrl_server());
            this.checkBox.setSelected(pd.isEnvio());
        } else {
            this.tx_servidor.setText(URL_SERVER_DEFAULT);
        }

    }

    protected Container createPair(String label, Component c, int minWidth) {
        Container pair = new Container(new BorderLayout());
        Label lb_text = new Label(label);
        Dimension d = lb_text.getPreferredSize();
        d.setWidth(Math.max(d.getWidth(), minWidth));
        lb_text.setPreferredSize(d);
        //lb_text.getStyle().setBgTransparency(100);
        pair.addComponent(BorderLayout.WEST, lb_text);
        pair.addComponent(BorderLayout.CENTER, c);
        return pair;
    }

    private void msgBox(int color, String titulo, String msnError) {
        setTintColor(color);
        Dialog.show(titulo.toUpperCase(), msnError, new Command("ok"), new Command[]{new Command("ok")}, Dialog.TYPE_CONFIRMATION, null, 0, CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, true, 500));
    }
}
